﻿using System;
using System.Web;
using PreguntaAlExperto.RulesLayer.Services;
using PreguntaAlExperto.TransporterObjectsFramework;
using PreguntaAlExperto.RulesLayer.Entities;
using Common;
using System.Xml.Serialization;
using System.Xml;
using System.Collections.Generic;

namespace PreguntaAlExperto
{
    public class RssHandler : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            List<Article> articles = ResolveQuery(context.Request);

            context.Response.ContentType = "application/xml";

            Rss orss = new Rss();
            Channel channel = new Channel();
            orss.Items = new Channel[] { channel };

            channel.Title = "Pregunta al Experto";
            channel.Link = "http://www.Preguntaalexperto.Net";
            channel.Description = "Pregunta al experto web site";
            channel.Language = "es-es";
            channel.Copyright = "Copyright © Pregunta al Experto, 2007-2008";
            channel.WebMaster = "info@preguntaalexperto.Net (Informacion)";
            channel.LastBuildDate = DateTime.Now.ToRfc822();
            channel.Ttl = articles.Count.ToString();
            channel.Generator = "C# hecho a manopla";
            channel.PubDate = DateTime.Now.ToRfc822();
            channel.Image = new rssChannelImage();
            channel.Image.Title = "Pregunta al Experto";
            channel.Image.Url = "http://www.Preguntaalexperto.Net/images/logoExpertoRss.Jpg";
            channel.Image.Width = "144";
            channel.Image.Height = "31";
            channel.Image.Link = "http://www.Preguntaalexperto.Net";
            channel.Image.Description = "Pregunta al Expero";

            channel.Item = new rssChannelItem[articles.Count];

            int i = 0;
            foreach (Article article in articles)
            {
                channel.Item[i] = new rssChannelItem();
                rssChannelItem item = channel.Item[i];

                item.Title = article.Title;
                item.Description = article.Short_Description; //articleContent; 
                item.Link = GetArticleLink(article.Path);
                item.Author = article.PublisherEntity.Name.WithoutSpanishChars();
                item.PubDate = article.Publish_Date.ToRfc822();
                item.Category = article.AllCategories;
                item.Guid = new rssChannelItemGuid();
                item.Guid.Value = article.Guid;
                item.Guid.IsPermaLink = "false";
                i++;
            }

            XmlSerializer serializer = new XmlSerializer(typeof(Rss));
            System.IO.Stream stream = new System.IO.MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(stream, System.Text.Encoding.UTF8);
            serializer.Serialize(writer, orss);
            writer.Flush();
            stream.Seek(0, System.IO.SeekOrigin.Begin);
            System.IO.StreamReader reader = new System.IO.StreamReader(stream, System.Text.Encoding.UTF8);

            string str = reader.ReadToEnd();

            str = str.Replace("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", "version=\"2.0\"");
            context.Response.Write(str);
        }

        #endregion

        private string GetArticleLink(string p)
        {
            return "http://www.preguntaalexperto.net/articles/" +
                System.IO.Path.GetFileName(p);
        }

        private List<Article> ResolveQuery(HttpRequest request)
        {
            string query = request.QueryString["q"];

            ArticlesService service = new ArticlesService();
            List<Article> articles = null;

            switch (query)
            {
                case "todos":
                    articles = service.getAllArticles(); 
                    break;
                case "10masvistos":
                    articles = service.getTopTeenVisited();
                    break;
                case "10masvotados":
                    articles = service.getTopTeenVoted();
                    break;
                case "publicador":
                    string publisher = request.QueryString["p"];
                    articles = service.getArticleByPublisherId(Int32.Parse(publisher));
                    break;
                case "categoria":
                    string categoria = request.QueryString["c"];
//                    articles = service.getArticleByPublisher(Int32.Parse(c));
                    break;
                default:
                    articles = service.getAllArticles();
                    break;
            }

            articles.Reverse();
            return articles; 
        }
    }
}
